package cn.com.roy.thread.t5_1_5.timertest5;



import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class Run2 {

    private static Timer timer = new Timer();
    private static int runCount = 0;

    static public class MyTask extends TimerTask {
        @Override
        public void run() {
            try {
                System.out.println("1 begine 运行了！时间为：" + new Date());
                Thread.sleep(5000);
                System.out.println("1    end 运行了！时间为：" + new Date());
                runCount ++ ;
                if(runCount == 5 ){
                    timer.cancel();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }

    //Timer类中的cancle方法有时候并没有争抢到queue锁，所以TimnerTask的任务继续正常执行
    public static void main(String[] args) {
        try {
            MyTask task = new MyTask();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateString = "2018-04-18 16:25:50";
            Date dateRef = sdf.parse(dateString);
            System.out.println("字符串时间为：" + dateRef.toLocaleString() + "当前时间为：" + new Date().toLocaleString());
            timer.schedule(task, dateRef,3000);
        } catch (ParseException e) {
            e.printStackTrace();
        }

    }

}
